const Koa = require('koa')
const app = new Koa()

const indent = (n) => new Array(n).join('&nbsp;')

// koa-componse
app.use(async (ctx, next) => {
  ctx.body = `<h1>请求第一层数据</h1>`
  await next() // 转移控制权
  ctx.body += `<h1>${JSON.stringify(ctx.state.user)}响应第一层数据</h1>`
})

app.use(async (ctx, next) => {
  ctx.body += `<h1>${indent(4)}请求第二层数据</h1>`
  await next()
  ctx.body += `<h1>${indent(4)}响应第二层数据</h1>`
})

app.use(async (ctx, next) => {
  ctx.body += `<h1>${indent(8)}请求第三层数据</h1>`
  await next()
  ctx.body += `<h1>${indent(8)}响应第三层数据</h1>`
})

app.use(async (ctx, next) => {
  // ctx.state 命名空间
  ctx.state.user = { name: 'devin', pwd: 123 }
  ctx.body += `<h4 style="color:red">${indent(16)}核心业务层</h4>`
})


app.listen(8080, () => {
  console.log('server port is 8080')
})